<?php
/**
 * Created by PhpStorm.
 * User: a21
 * Date: 2017/2/16
 * Time: 上午10:29
 */

class EmptyAction extends Action{
    private function copyuserinfo(){
        //同步用户信息

        $clientId = getenv('clientId');
        $clientSecret = getenv('clientSecret');
        $address = getenv('address');

        $url = $address . "ecloud/oapi/token";

        $post_data = array("grantType"=>"client_credentials",
            "clientId"=>$clientId,
            "clientSecret"=>$clientSecret);

        $post_json = json_encode($post_data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,CURLOPT_TIMEOUT,60);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_json);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Contnet-Length:'.strlen($post_json)
        ));
        $infojson = curl_exec($ch);//运行curl
        curl_close($ch);

        $infodata = json_decode(trim($infojson),true);
        if (isset($infodata['accessToken']) && !empty($infodata['accessToken'])){
            $getstr = $address . 'ecloud/oapi/user?token='.$infodata['accessToken'];
            //初始化
            $ch = curl_init();
            //设置选项，包括URL
            curl_setopt($ch, CURLOPT_URL, $getstr);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch,CURLOPT_TIMEOUT,60);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            //执行并获取HTML文档内容
            $output = curl_exec($ch);
            //释放curl句柄
            curl_close($ch);

            $userdata = json_decode(trim($output),true);

            if (isset($userdata['entity']) && !empty($userdata['entity'])){
                $users = M('user');

                foreach ($userdata['entity'] as $infodata){
                    $condition['name'] = $infodata['username'];
                    $count = $users->where($condition)->count();

                    $newdata['companyId'] = $infodata['companyId'];
                    $newdata['companyUserId'] = $infodata['companyUserId'];
                    $newdata['email'] = $infodata['email'];
                    $newdata['employeeName'] = $infodata['employeeName'];
                    $newdata['employeeNo'] = $infodata['employeeNo'];
                    $newdata['telephone'] = $infodata['phone'];
                    $newdata['name'] = $infodata['username'];

                    if ($count <= 0){
                        $newdata['category_id'] = 0;
                        $newdata['status'] = 0;

                        $users->add($newdata);


                    }else{

                        $users->where($condition)->save($newdata);
                    }

                }
                $tempres = 'success';
                return $tempres;
            }else{
                $tempres = '用户信息同步失败,user->entity为空';
                return $tempres;
            }
        }else{
            $tempres = '用户信息同步失败,token无效';
            return $tempres;
        }
    }
    private function copycompanyinfo(){
        //同步公司部门架构
        $address = getenv('address');
        $url = $address . "ecloud/oapi/token";
        $clientId = getenv('clientId');
        $clientSecret = getenv('clientSecret');
        $post_data = array("grantType"=>"client_credentials",
            "clientId"=>$clientId,
            "clientSecret"=>$clientSecret);

        $post_json = json_encode($post_data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_json);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Contnet-Length:'.strlen($post_json)
        ));
        $infojson = curl_exec($ch);//运行curl
        curl_close($ch);

        $infodata = json_decode(trim($infojson),true);
        if (isset($infodata['accessToken']) && !empty($infodata['accessToken'])){
            $getstr = $address . 'ecloud/oapi/department?token='.$infodata['accessToken'];
            //初始化
            $ch = curl_init();
            //设置选项，包括URL
            curl_setopt($ch, CURLOPT_URL, $getstr);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch,CURLOPT_TIMEOUT,60);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            //执行并获取HTML文档内容
            $output = curl_exec($ch);
            //释放curl句柄
            curl_close($ch);

            $userdata = json_decode(trim($output),true);
            if (isset($userdata['entity']) && !empty($userdata['entity'])){

                $this->updateCompany($userdata['entity']);

                $r_department = M('Role_department');
                $r_data = $r_department->select();
                $m_position = M('Position');
                foreach ($r_data as $val){

                    $p_condition['department_id'] = $val['department_id'];
                    $d_count = $m_position->where($p_condition)->count();
                    if ($d_count <= 0){
                        $position['parent_id'] = $val['parent_id'] ? $val['parent_id'] : 0;
                        $position['name'] = '未分配职位';
                        $position['department_id'] = $val['department_id'];
                        $m_position->add($position);
                    }else{
                        $position['parent_id'] = $val['parent_id'] ? $val['parent_id'] : 0;
                        $position['name'] = '未分配职位';
                        $position['department_id'] = $val['department_id'];
                        $m_position->where($p_condition)->save($position);
                    }
                }


                $tempres = 'success';
                return $tempres;
                print_r('公司部门架构同步成功');
            }else{
                $tempres = '公司部门架构同步失败,user->entity为空';
                return $tempres;
            }
        }else{
            $tempres = '公司部门架构同步失败,token无效';
            return $tempres;
        }
    }
    private function copyuserdepartment(){
        //同步用户对应部门信息
        $address = getenv('address');
        $url = $address . "ecloud/oapi/token";
        $clientId = getenv('clientId');
        $clientSecret = getenv('clientSecret');
        $post_data = array("grantType"=>"client_credentials",
            "clientId"=>$clientId,
            "clientSecret"=>$clientSecret);

        $post_json = json_encode($post_data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_TIMEOUT,60);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_json);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Contnet-Length:'.strlen($post_json)
        ));
        $infojson = curl_exec($ch);//运行curl
        curl_close($ch);

        $infodata = json_decode(trim($infojson),true);
        if (isset($infodata['accessToken']) && !empty($infodata['accessToken'])) {
            $getstr = $address . 'ecloud/oapi/user_department?token=' . $infodata['accessToken'].'&operation=sync';
            //初始化
            $ch = curl_init();
            //设置选项，包括URL
            curl_setopt($ch, CURLOPT_URL, $getstr);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch,CURLOPT_TIMEOUT,60);
            //执行并获取HTML文档内容
            $output = curl_exec($ch);
            //释放curl句柄
            curl_close($ch);

            $userdata = json_decode(trim($output), true);
            if (isset($userdata['entity']) && !empty($userdata['entity'])){

                $d_user = M('User');
                $m_role = M('Role');
                $m_position = M('position');

                $condition['category_id'] = array('neq',0);
                $d_user->where($condition)->save(array('category_id'=>0));

                foreach ($userdata['entity'] as $val){
                    $u_condition['name'] = $val['username'];


                    $user = $d_user->where($u_condition)->find();
                    $r_cond['user_id'] = $user['user_id'];
                    $r_count = $m_role->where($r_cond)->count();

                    if ($r_count <= 0){
                        $de_condition['department_id'] = $val['departmentId'];
                        $posit = $m_position->where($de_condition)->find();
                        if ($posit){
                            $r_condition['position_id'] = $posit['position_id'];
                            $r_condition['user_id'] = $user['user_id'];
                            $m_role->add($r_condition);
                        }

                    }

                    $r_id = $m_role->where($r_cond)->find();
                    if ($r_id){
                        $update_id['role_id'] = $r_id['role_id'];
                        $d_user->where($u_condition)->save($update_id);
                    }

                    if ($val['roleType'] == 'adm'){
                        $res_admin['category_id'] = 1;
                        $res_admin['status'] = 1;
                        $d_user->where($u_condition)->save($res_admin);
                    }else{
                        $res_admin['category_id'] = 0;
                        $res_admin['status'] = 1;
                        $d_user->where($u_condition)->save($res_admin);
                    }

                }
                $tempres = 'success';
                return $tempres;
            }else{
                $tempres = '用户对应部门信息同步失败,user->entity为空';
                return $tempres;
            }
        }else{
            $tempres = '用户对应部门信息同步失败,token无效';
            return $tempres;
        }
    }
    public function index(){
        $paramName = MODULE_NAME;
        if (strtolower($paramName) == "autologin"){
            //授权登录
            $code = $this->_get('code');
            if (!isset($code) || empty($code)) return;
            $clientId = getenv('clientId');
            $clientSecret = getenv('clientSecret');
            $redirectUri = getenv('redirectUrl');
            $address = getenv('address');
            $url = $address . "ecloud/oapi/token";
            $post_data = array ("grantType"=>"authorization_code",
                "code"=>$code,
                "redirectUri"=>$redirectUri,
                "clientId"=>$clientId,
                "clientSecret"=>$clientSecret);
            $post_json = json_encode($post_data);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch,CURLOPT_TIMEOUT,60);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            // post数据
            curl_setopt($ch, CURLOPT_POST, 1);
            // post的变量
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_json);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Contnet-Length:'.strlen($post_json)
            ));
            $json = curl_exec($ch);//运行curl
            curl_close($ch);

            $data = json_decode(trim($json),true);

            if (isset($data['user']) && !empty($data['user'])) {
                $d_user = M('user');


                $user = $d_user->where(array('name' => $data['user']['username']))->find();

                if (!isset($user['name']) || empty($user['name'])) {
                    $userInfo['category_id'] = 0;
                    $userInfo['status'] = 1;
                    $userInfo['name'] = $data['user']['username'];
                    $userInfo['companyUserId'] = $data['user']['id'];
                    $userInfo['companyId'] = $data['user']['companyId'];
                    $d_user->add($userInfo);
                    $user = $d_user->where(array('name' => $data['user']['username']))->find();
                }
                if ($user['category_id'] == 1) {
                    session('admin', 1);
                }
                session(array('expire'=>3600));
                $d_role = D('RoleView');
                $role = $d_role->where('user.user_id = %d', $user['user_id'])->find();
                if ($role && !empty($role['role_id'])){
                    session('role_id', $role['role_id']);
                    session('user_img', $user['img']);
                    session('position_id', $role['position_id']);
                    session('role_name', $role['role_name']);
                    session('department_id', $role['department_id']);
                    session('name', $user['name']);
                    session('user_id', $user['user_id']);

                    alert('success', L('LOGIN_SUCCESS'), U('Index/index'));
                }else{
                    alert('error', L('HAVE_NO_POSITION'),U('User/login'));
                }

            }else{
                alert('error','code已过期',U('User/login'));
            }
        }elseif (strtolower($paramName) == 'updatealldata'){
            $syncId = $_GET['id']; //回传
            if (!isset($syncId) || empty($syncId)) return;

            header('Content-type: application/json');
            $result['result'] = 'success';
            $result['id'] = $syncId;
            echo json_encode($result);

            $userRes = $this->copyuserinfo();
            $companyRes = $this->copycompanyinfo();
            $userDepartmentRes = $this->copyuserdepartment();
            $address = getenv('address');
            $url = $address . 'ecloud/portal/sync/'.$syncId;
            if (strlen($userRes) > 0 && strlen($companyRes) > 0 && strlen($userDepartmentRes) > 0) {
                if ($userRes == 'success' && $companyRes == 'success' && $userDepartmentRes == 'success') {

                    $post_data['result'] = 'success';
                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $url);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    curl_setopt($ch,CURLOPT_TIMEOUT,60);
                    // post数据
                    curl_setopt($ch, CURLOPT_POST, 1);
                    // post的变量
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
                    // curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    //     'Contnet-Length:'.strlen($post_json)
                    // ));
                    $json = curl_exec($ch);//运行curl
                    curl_close($ch);
                } else {
                    $post_data['result'] = 'failure';
                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $url);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    curl_setopt($ch,CURLOPT_TIMEOUT,60);
                    // post数据
                    curl_setopt($ch, CURLOPT_POST, 1);
                    // post的变量
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
                    // curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    //     'Contnet-Length:'.strlen($post_json)
                    // ));
                    $json = curl_exec($ch);//运行curl
                    curl_close($ch);
                }
            }

        }
    }

    /*递归遍历*/
    private function updateCompany($infoArr){

        $de_role = M('role_department');

        $condition['department_id'] = $infoArr['departmentId'];
        $count = $de_role->where($condition)->count();

        $newdata['department_id'] = $infoArr['departmentId'];
        $newdata['parent_id'] = $infoArr['parentId'] ? $infoArr['parentId'] : 0;
        $newdata['name'] = $infoArr['nodeName'];

        if ($count <= 0){
            $de_role->add($newdata);
        }else{
            $de_role->where($condition)->save($newdata);
        }

        if (!is_array ($infoArr['children']) || empty($infoArr['children'])) return;

        foreach ($infoArr['children'] as $val )
        {

                $this->updateCompany($val);

        }

    }

}